﻿class_name MeleeWeaponBase
extends WeaponBase

# 近战武器特有属性
var attack_range: float = 1.0
var attack_arc: float   = 60.0  # 攻击弧度（度）

# 组件引用
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var attack_area: Area2D = $AttackArea


func _ready() -> void:
	super.baseReady()

	# 连接动画完成信号
	if animated_sprite and not animated_sprite.animation_finished.is_connected(_on_animation_finished):
		animated_sprite.animation_finished.connect(_on_animation_finished)


func load_weapon_data() -> void:
	super.load_weapon_data()

	var data = WeaponDataManager.get_weapon_data(weapon_id)
	if data.is_empty():
		return

	attack_range = data.get("attack_range", 1.0)
	attack_arc = data.get("attack_arc", 60.0)

	# 配置攻击区域
	configure_attack_area()


# 配置攻击区域
func configure_attack_area() -> void:
	# 子类可以覆盖这个方法来设置特定形状的攻击区域
	pass


# 攻击实现
func attack() -> void:
	if not can_attack:
		return

	super.attack()

	# 播放攻击动画
	var anim_name: String = weapon_id + "_attack"
	if animated_sprite.sprite_frames.has_animation(anim_name):
		animated_sprite.play(anim_name)
	else:
		# 如果没有特定武器的动画，播放默认动画
		animated_sprite.play("attack")
		# 直接结束攻击，因为没有动画可以触发结束事件
		_finish_attack()


# 当攻击动画完成时
func _on_animation_finished() -> void:
	if animated_sprite.animation.ends_with("_attack"):
		_finish_attack()
		# 切换回默认动画
		var default_anim: String = weapon_id + "_default"
		if animated_sprite.sprite_frames.has_animation(default_anim):
			animated_sprite.play(default_anim)
		else:
			animated_sprite.play("default")


# 处理翻转
func handle_flip(flip_h: bool) -> void:
	if animated_sprite:
		animated_sprite.flip_h = flip_h